<script>
  import config from './config'
  import { getToken } from '@/utils/auth'
  import request from '@/utils/request'
  import { getMpOpenId } from '@/api/login'

  export default {
    onLaunch: function() {
      //静默获取openid
      this.getWechatOpenId()
      this.initApp()
    },
    methods: {
      // 静默获取微信服务号openid
      async getWechatOpenId() {
        //#ifdef H5
        // 只在H5环境下执行
        try {
          // 检查是否已有openid缓存
          let openid = uni.getStorageSync('wechat_openid')
          if (openid) {
            console.log('已有openid缓存:', openid)
            return
          }
          
          // 检查是否在微信浏览器中
          const isWechat = this.isWechatBrowser()
          if (!isWechat) {
            console.log('非微信浏览器，跳过openid获取')
            return
          }
          
          // 获取URL中的code参数
          const urlParams = new URLSearchParams(window.location.search)
          const code = urlParams.get('code')
          
          if (!code) {
            // 没有code，跳转到微信授权页获取code
            this.redirectToWechatAuth()
            return
          }
          
          // 有code，调用后端接口换取openid
          await this.exchangeCodeForOpenId(code)
          
        } catch (error) {
          console.error('获取openid失败:', error)
        }
        //#endif
      },
      
      // 检查是否在微信浏览器中
      isWechatBrowser() {
        const ua = navigator.userAgent.toLowerCase()
        return ua.includes('micromessenger')
      },
      
              // 跳转到微信授权页
        redirectToWechatAuth() {
          const appid = 'wx4636c14a03145741' // 替换为你的服务号appid
          const redirectUri = encodeURIComponent(window.location.href)
          const scope = 'snsapi_base' // 静默授权，不弹出授权页面
          const state = 'STATE'
        
        const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
        
        console.log('跳转到微信授权页:', authUrl)
        window.location.href = authUrl
      },
      
      // 用code换取openid
      async exchangeCodeForOpenId(code) {
        try {
          const res = await getMpOpenId(code)
          
          if (res.code === 200 && res.openid) {
            const openid = res.openid
            uni.setStorageSync('wechat_openid', openid)
            console.log('成功获取openid:', openid)
          } else {
            console.error('换取openid失败:', res)
          }
        } catch (error) {
          console.error('换取openid异常:', error)
        }
      },
      
      // 初始化应用
      initApp() {
        // 初始化应用配置
        this.initConfig()
        // 检查用户登录状态
        //#ifdef H5
        this.checkLogin()
        //#endif
      },
      initConfig() {
        this.globalData.config = config
      },
      checkLogin() {
        // 白名单页面路径
        const whiteList = [
          '',
          '/pages/login',
          '/pages/register',
          '/pages/common/webview/index',
          '/pages/mine/payment/index',
          '/pages/mine/maintenance/index',
          '/pages/mine/accesscard/index',
          '/pages/mine/maintenance/payConfirm'
        ];
        // 获取当前页面路径
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const currentPath = currentPage ? ('/' + currentPage.route) : '';
        // 判断是否在白名单
        if (whiteList.includes(currentPath)) {
          return;
        }
        // debugger
        // if (!getToken()) {
        //   this.$tab.reLaunch('/pages/login') 
        // }
      }
    }
  }
</script>

<style lang="scss">
  @import '@/static/scss/index.scss';
  @import '@/static/font/iconfont.css';
</style>
